<template>
  <div>
    <table class="classTimeTable" cellpadding="0" cellspacing="0">
      <tr style="background-color: #EAEBF3">
        <th>{{$t('arrangement.timesAndWeek')}}</th>
        <th>{{$t('common.week2.1')}}</th>
        <th>{{$t('common.week2.2')}}</th>
        <th>{{$t('common.week2.3')}}</th>
        <th>{{$t('common.week2.4')}}</th>
        <th>{{$t('common.week2.5')}}</th>
        <th>{{$t('common.week2.6')}}</th>
        <th>{{$t('common.week2.7')}}</th>
      </tr>
      <tr v-for="(weekList, i) in this.classTables" :key="i"
        :style="{backgroundColor: trBackground(i)}" >
        <template v-for="(week, j) in weekList">
          <td :key="j"
            v-if="!week.remove"
            :rowspan="week.rowspan"
            :data-index="week.dayOfWeek"
            @click="OnCellClick(week)"
            :class="{
              'seletedClass': week.selected,
              'weekHeader': j == 0,
              'is12': i == 11,
              'half':week.half,
              'both':week.both,
              'pointer': (canClick && week.disable)
            }"
          >
               <!--  :title="`[${$t('common.week.'+j)} 第${i+1}节] 排课信息`" -->
               <div v-if="week.popover && week.popover.length ">
                <el-popover
                :width="400"
                :title="`[${$t('common.week.'+j)}] 排课信息`"
                placement="right-start"
                trigger="hover">
                <div style="padding-top:2px;max-height:400px;overflow-y:auto">
                  <div
                    style="padding:0;font-size:12px;line-height:14px;"
                    v-for="item in week.popover"
                    :key="item">
                    {{item}}
                    </div>
                </div>
              <div slot="reference" :style="week.style" :class="{'disable': week.disable, 'bg-red': week.chongtu}">
                     <div
                        :style="item.style"
                        v-for=" item in week.label"
                        :key="item.value"
                     >{{item.value}}</div>
              </div>
             </el-popover>
             </div>
             <div v-else-if="week.popover === null" :style="week.style" :class="{'disable': week.disable, 'bg-red': week.chongtu}">
                  {{week.label}}
              </div>
              <div v-else :style="week.style" :class="{'disable': week.disable, 'bg-red': week.chongtu}">
                    <div
                        :style="item.style"
                        v-for=" item in week.label"
                        :key="item.value"
                     >
                     {{item.value}}</div>
              </div>
          </td>
        </template>
      </tr>
    </table>
  </div>
</template>
<script>
import UTILS from "common/src/utils/utils";

// 课程时间表组件
export default {
  name: "LessonTimeTable",
  props: ["data", "cellClickCallback"],
  computed: {
    canClick(){
      return !_.isNil(this.cellClickCallback);
    }
  },
  mounted() {
    this.initWeekList();
  },
  watch: {
    data: {
      handler: function(newVal, oldVal) {
        this.initWeekList();
        // if (newVal) {
        //   this.fillTable(newVal);
        // }
      }
    }
  },
  data() {
    return {
      classTables: [], //二维数组 节次->星期
      dataList: ['' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , '11' , '12' ],
      disPlayLine: ""
    };
  },
  methods: {
    displayClassTimes(val) {
      let language = this.$store.getters.language;
      return language == "cn" ? "第" + val + "节课" : "Class " + val;
    },
    trBackground(index){
      if(index == 11) {
        return '#fff2f3';
      }
      return _.includes([0, 1, 4, 5, 8, 9], index) ?'#ffffff':'#F6F7FB';
    },
    initWeekList() {
      this.classTables = [];
      for (let i = 1; i < 13; i++) {
        let cellClass;
        if (i % 2) {
          cellClass = "half";
        }
        let weekList = [{
          dayOfWeek: 0, timeClass: i, disable: false,
          label: this.displayClassTimes(this.dataList[i]),
          half: cellClass === "half",
          popover: null
        }];
        for (let j = 1; j <= 7; j++) {
          weekList.push({
            selected: false,
            dayOfWeek: j,
            timeClass: i,
            half: cellClass === "half",
            both: cellClass === "both",
            popover: null
          });
        }
        this.classTables.push(weekList);
      }
      this.fillTable();
    },
    // 多个课程有冲突时，value和popover值有重复添加问题，只追加当前的内容
    formatValue(item={}, value){
      const curValList = item[value].split(";")
      const curVal = curValList.find(val=>val.includes(item.teacherCode)) || ""
      return curVal
    },
    fillTable() {
      if(this.data) {
        this.data.forEach((time, index) => {
          time.rowend = false;
          time.newTimeEnd = null;
          time.remove = false;
          time.redcolor = false;
          if(time.label) {
            time.value = time.label
          }
          if(!time.popover) {
            let start = time.value.indexOf('[')
            let end = time.value.indexOf(']')
            let jieci = time.value.substring(start, end+1)
            let room = time.value.substring(0,start)
            let adr = time.value.substring(end+1)
            time.popover = '['+String(time.timeStart)+'-'+String(time.timeEnd)+'节] '+ jieci + ' ' + room + ' ' + adr
          }
        })
      }
      if (this.data) {
        // 冲突处理
        this.data.forEach((time, index) => {
          for (let j = index + 1; j < this.data.length; j++) {
            const _time = this.data[j];
            if (time.dayOfWeek == _time.dayOfWeek) {
                if(time.timeStart == _time.timeStart || time.timeEnd == _time.timeEnd) {
                    if(time.timeStart == _time.timeStart && time.timeEnd >= _time.timeEnd ||
                    time.timeEnd == _time.timeEnd && time.timeStart <= _time.timeStart) {
                      time.value+=";" + _time.value;
                      time.popover+=";" + _time.popover;
                      _time.remove = true;
                    }else {
                      _time.value+=";" + time.value;
                      _time.popover+=";" + time.popover;
                      time.remove = true;
                    }
                  if(time.courseCode !== _time.courseCode) {
                    if(_.intersection(time.weeks,_time.weeks).length > 0){
                      _time.redcolor = true;
                      time.redcolor = true;
                    }
                  }
                }else if(time.timeStart == _time.timeEnd || time.timeEnd == _time.timeStart){
                      if(time.timeStart == _time.timeEnd) {
                          time.value+=";" + _time.value;
                          _time.newTimeEnd = time.timeStart-1;
                          _time.rowend = true;
                          _time.popover+=";" + time.popover;
                      } else {
                          _time.value+=";" + time.value;
                          time.newTimeEnd = _time.timeStart-1;
                          time.rowend = true;
                          time.popover+=";" + _time.popover;
                      }
                      if(time.courseCode !== _time.courseCode) {
                        if(_.intersection(time.weeks,_time.weeks).length > 0){
                          _time.redcolor = true;
                          time.redcolor = true;
                        }
                      }
                }else if(time.timeEnd > _time.timeStart && time.timeEnd < _time.timeEnd) {
                  _time.value+=";" + this.formatValue(time, "value");
                  _time.popover+=";" + this.formatValue(time, "popover");
                  // _time.value+=";" + time.value;
                  // _time.popover+=";" + time.popover;
                  time.newTimeEnd = _time.timeStart-1;
                  time.rowend = true;
                  if(time.courseCode !== _time.courseCode) {
                    if(_.intersection(time.weeks,_time.weeks).length > 0){
                      _time.redcolor = true;
                      time.redcolor = true;
                    }
                  }
                } else if (time.timeEnd > _time.timeEnd && time.timeStart < _time.timeEnd) {
                  time.value+=";" + this.formatValue(_time, "value");
                  time.popover+=";" + this.formatValue(_time, "popover");
                  // time.value+=";" + _time.value;
                  // time.popover+=";" + _time.popover;
                  _time.newTimeEnd = time.timeStart-1;
                  _time.rowend = true;
                  if(time.courseCode !== _time.courseCode) {
                    if(_.intersection(time.weeks,_time.weeks).length > 0){
                      _time.redcolor = true;
                      time.redcolor = true;
                    }
                  }
                }
            }
          }
        });
        this.data.forEach(time => {
          if (time.remove) {
            return;
          }
          const week = this.classTables[time.timeStart - 1][time.dayOfWeek];
         // week.label = time.value;
          week.label = [];
          const temp = time.value.split(";");
          for (const item of temp) {
            if(item) {
               week.label.push({
                 value: item,
                 style: "padding:2px 0 0;border-bottom:dashed 1px #bbb;overflow: hidden;"
               });
            }
          }
          week.label[week.label.length-1].style = "overflow: hidden;";
          week.title = time.label;
          week.chongtu = time.redcolor;
          week.disable = true;
          if(time.rowend) {
            week.rowspan = time.newTimeEnd - time.timeStart + 1;
          } else {
            week.rowspan = time.timeEnd - time.timeStart + 1;
          }
          week.style = {
            height: 45 * week.rowspan + "px",
          };
          week.popover =  this.getPopover(time);
          // 之后的节次都需要合并单元格
          if(time.rowend) {
            for (let step = time.timeStart + 1; step <= time.newTimeEnd; step++) {
              const nextTime = this.classTables[step - 1][time.dayOfWeek];
              _.merge(nextTime, {
                label: "",
                disable: true,
                remove: true
              });
            }
          } else {
            for (let step = time.timeStart + 1; step <= time.timeEnd; step++) {
              const nextTime = this.classTables[step - 1][time.dayOfWeek];
              _.merge(nextTime, {
                label: "",
                disable: true,
                remove: true
              });
            }
          }
        });
      }
    },
    getPopover(data) {
      //  let temp = [];
      //  if(data) {
      //     let labels = data.value.split(";");
      //     temp.push({
      //       value: "[" + data.timeStart + "-" + data.timeEnd + "] " + (data.label ? data.label : data.value)
      //     });
      //     if(data.classBegin) {
      //         let classBegins = data.classBegin.split(";")
      //         for (let i = 1; i < labels.length; i++) {
      //               temp.push({
      //                 value: classBegins[i-1] ? classBegins[i-1] : classBegins[i-2] + " " + labels[i]
      //               })
      //         }
      //     }

      //  }
       let temp = [];
       if(data) {
         if(data.popover) {
           let popovers = data.popover.split(";");
            for (const item of popovers) {
               if(item && item !== 'undefined') {
                 temp.push(item);
               }
            }
          }
         }
          return Array.from(new Set(temp));

    },
    OnCellClick(week) {
      if (this.canClick && week.disable) {
        if (this.data) {
          for (let i = 0; i < this.data.length; i++) {
            const time = this.data[i];
            if (
              time.dayOfWeek == week.dayOfWeek &&
              (time.timeStart <= week.timeClass && time.timeEnd >= week.timeClass)
            ) {
              week.selected = true;
              week.timeData = time;
              break;
            }
          }
        }
        if (week.timeData){
          this.cellClickCallback(week.timeData);
        } else {
          this.cellClickCallback({
            dayOfWeek: week.dayOfWeek,
            timeStart: week.timeClass,
            timeEnd: week.timeClass,
            value: "已选"
          });
        }
      }

      if(!week.label) {
        this.$emit("chooseCourse",week);
      }
    },
  }
};
</script>
<style lang="scss" scoped>
::-webkit-scrollbar {
  width: 9px !important;
  height: 10px !important;
}
.bg-red {
  color: red !important
}
.classTimeTable {
  table-layout: fixed;
  &.noPoint td {
    cursor: default;
    width: auto;
  }
  border-collapse: collapse;
  width: 100%;
  text-align: center;
  font-size: 12px;
  th {
    color: #2B3B4E;
    height: 26px;
    border: solid 1px #E7E8E8;
  }
  td {
    height: 26px;
    border: solid 1px #E7E8E8;
    border-top: none;
    &.weekHeader{
      color: #4C5C70;
      &.is12 {
        color: #F25A67;
      }
    }
    &.pointer {
      cursor: pointer;
    }
    div {
      line-height: 16px;
      overflow: auto;
      text-overflow: ellipsis;
      padding: 4px;
      &.disable {
        color: #fff;
        background-color: #705BCF;
        border-radius: 2px;
        overflow: overlay;
      }
    }
    &.both {
      border: solid 1px #E7E8E8;
    }
    &.half {
      border-bottom: dashed 1px #E7E8E8;
    }
    &.seletedClass {
      background-color: yellow !important;
    }

  }
}
</style>
